package cn.ulc.socket.admin.service.template.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.ulc.common.constant.PubDataConstant;
import cn.ulc.common.constant.enums.AvailableStatus;
import cn.ulc.common.constant.enums.DeletedStatus;
import cn.ulc.common.exception.PlatformException;
import cn.ulc.common.model.param.PaginationParam;
import cn.ulc.socket.admin.common.BaseService;
import cn.ulc.socket.admin.model.dto.template.TemplateDTO;
import cn.ulc.socket.admin.model.dto.template.TemplateDetailDTO;
import cn.ulc.socket.admin.model.dto.template.TemplateListDTO;
import cn.ulc.socket.admin.model.param.template.TemplateCompanyParam;
import cn.ulc.socket.admin.model.param.template.TemplateContentParam;
import cn.ulc.socket.admin.model.param.template.TemplateSaveParam;
import cn.ulc.socket.admin.service.template.TemplateServ;
import cn.ulc.store.dao.CompanyDao;
import cn.ulc.store.dao.template.*;
import cn.ulc.store.entity.Company;
import cn.ulc.store.entity.template.*;
import lombok.AllArgsConstructor;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@AllArgsConstructor
public class TemplateServImpl extends BaseService implements TemplateServ {

    CompanyDao companyDao;
    TemplateDao templateDao;
    TemplateBannerDao bannerDao;
    TemplateCategoryDao categoryDao;
    TemplateBlockDao blockDao ;
    TemplateBlockGoodsDao blockGoodsDao ;

    @Override
    public TemplateListDTO findListPage(String key, String status, PaginationParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",key);
        condition.put("status",status);
        PageQuery pageQuery = initPageQuery(param);
        pageQuery.setParas(condition);
        templateDao.findListPage(pageQuery);
        return new TemplateListDTO(pageQuery.getList(),pageQuery.getTotalRow());
    }

    @Override
    public TemplateDTO findOne(Long id) {
        long tid = Convert.toLong(id,0l);
        return TemplateDTO.builder().model(templateDao.findOne(tid)).build();
    }

    @Override
    public Long save(TemplateSaveParam param) {
        Company company = getCurrentCompany();
        boolean isEdit = param.getId() != null && param.getId() > 0;
        Template entity = new Template();
        if(isEdit){
            entity = templateDao.findOne(param.getId());
            if(entity == null) throw new PlatformException("未检索到模板信息");
        }else{
            int maxSort = templateDao.findMaxSort(company.getId());
            entity.setStatus(AvailableStatus.AVAILABLE);
            entity.setSort(maxSort+1);
        }
        setBaseInfo(entity);
        entity.setName(param.getName());
        entity.setCoverUrl(param.getCoverUrl());
        entity.setBgUrl(param.getBgUrl());
        templateDao.save(entity);
        return entity.getId();
    }

    @Override
    public Boolean changeStatus(Long id, AvailableStatus status) {
        long templateId = Convert.toLong(id,0l);
        Template entity = templateDao.findOne(templateId);
        if (entity == null)  throw new PlatformException("未检索到模板信息");
        entity.setStatus(status);
        setBaseInfo(entity);
        templateDao.save(entity);
        return true;
    }

    @Override
    public Boolean deleted(Long id) {
        long templateId = Convert.toLong(id,0l);
        Template entity = templateDao.findOne(templateId);
        if (entity != null) {
            setBaseInfo(entity);
            entity.setDeleted(DeletedStatus.DELETED);
            templateDao.save(entity);
        }
        return true;
    }

    @Override
    public Company findCompanyInfo() {
        Company company = getCurrentCompany();
        return company;
    }

    @Override
    public Long saveCompany(TemplateCompanyParam param) {
        Company entity = getCurrentCompany();
        setBaseInfo(entity);
        if(StrUtil.isNotBlank(param.getName())){
            entity.setName(param.getName());
        }
        if(StrUtil.isNotBlank(param.getLogo())){
            entity.setLogo(param.getLogo());
        }
        companyDao.save(entity);
        return entity.getId();
    }

    @Override
    public TemplateDetailDTO findContent(Long id) {
        if(id == null || id <= 0) throw new PlatformException("参数错误");
        Company company = getCurrentCompany();
        List<TemplateCategory> categoryList = categoryDao.findByTemplate(id);
        List<TemplateBanner> bannerList = bannerDao.findByTemplate(id);
        List<TemplateBlock> blockList = blockDao.findByTemplate(id);
        if(blockList !=null && blockList.size()>0){
            for (TemplateBlock templateBlock : blockList) {
                templateBlock.setGoodsList( blockGoodsDao.findByTemplateBlock(templateBlock.getId()) );
            }
        }
        return TemplateDetailDTO.builder().company(company).categoryList(categoryList).bannerList(bannerList).blockList(blockList).build();
    }

    @Override
    @Transactional
    public Long saveContent(TemplateContentParam param) {
        if(param == null || param.getTemplateId() == null ||param.getTemplateId()==0) throw new PlatformException("参数错误");
        Company paramCompany = param.getCompany();
        if(!isNullObject(paramCompany)) {
            Company company = getCurrentCompany();
            company.setName(paramCompany.getName());
            company.setTemplateId(param.getTemplateId());
            setBaseInfo(company);
            int result = companyDao.save(company);
            if(result <=0) throw new PlatformException("店铺信息更新失败");
        }
        List<TemplateBanner> bannerList = param.getBannerList();
        if(bannerList != null && bannerList.size()>0){
            bannerList.parallelStream().forEach(t -> {
                if(t.getLinkType() != null && t.getLinkType() == PubDataConstant.LINK_TYPE_OUT && !t.getLinkUrl().startsWith("http")) t.setLinkUrl("http://"+t.getLinkUrl());
                setBaseInfo(t);
                t.setTemplateId(param.getTemplateId());
            });
            bannerDao.saveAll(bannerList);
        }
        List<TemplateCategory> categoryList = param.getCategoryList();
        if(categoryList != null && categoryList.size()>0){
            categoryList.parallelStream().forEach(t -> {
                if(t.getLinkType() != null && t.getLinkType() == PubDataConstant.LINK_TYPE_OUT && !t.getLinkUrl().startsWith("http")) t.setLinkUrl("http://"+t.getLinkUrl());
                setBaseInfo(t);
                t.setTemplateId(param.getTemplateId());
            });
            categoryDao.saveAll(categoryList);
        }
        List<TemplateBlock> blockList = param.getBlockList();
        if(blockList != null && blockList.size()>0){
            List<TemplateBlockGoods> goodsSaveList = new ArrayList<>();
            for (TemplateBlock block : blockList) {
                block.setTemplateId(param.getTemplateId());
                setBaseInfo(block);
                List<TemplateBlockGoods> bookList = block.getGoodsList();
                if(bookList != null && bookList.size()>0){
                    for (TemplateBlockGoods goods : bookList) {
                        goods.setTemplateBlockId( block.getId() );
                        goods.setTemplateId(param.getTemplateId());
                        setBaseInfo(goods);
                        goodsSaveList.add(goods);
                    }
                }
            }
            blockDao.saveAll(blockList);
            blockGoodsDao.saveAll(goodsSaveList);
        }
        return param.getTemplateId();
    }
}
